package com.wbao.dianniu.utils;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;

import com.alibaba.mobileim.channel.util.FileUtils;
import com.arlen.photo.photopickup.presenter.HeadPresenter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.FutureTarget;
import com.bumptech.glide.request.target.Target;

import java.io.File;

/**
 * Created by Administrator on 2017/8/2.
 */

public class Downloader {

    public static void download(final Context context, final String url) {
        new AsyncTask(){
            @Override
            protected Object doInBackground(Object[] params) {
                File file = null;
                try {
                    FutureTarget future = Glide.with(context)
                            .load(url)
                            .downloadOnly(Target.SIZE_ORIGINAL,Target.SIZE_ORIGINAL);
                    file = (File)future.get();
                    // 首先保存图片
//                    File pictureFolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsoluteFile();
//                    File pictureFolder = Environment.getExternalStorageDirectory().getPath() + Environment.
//                    File appDir = new File(pictureFolder ,"DianniuImage");
                    File appDir = new File(HeadPresenter.getImageCacheDir(context));
                    if (!appDir.exists()) {
                        appDir.mkdirs();
                    }
                    String fileName = System.currentTimeMillis() + ".jpg";
                    File destFile = new File(appDir, fileName);
                    FileUtils.copyFile(file, destFile);

                    // 对7.0以上系统兼容
//                    Uri uri = Uri.fromFile(new File(destFile.getPath()));
                    Uri uri = PermissionUtils.getInstance().openUri(new File(destFile.getPath()));

                    // 最后通知图库更新
                    context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
                } catch (Exception e){
                    e.printStackTrace();
                }

                return file;
            }

            @Override
            protected void onPostExecute(Object o) {
                Notification.showToastMsg(context, "图片已保存到：" + HeadPresenter.getImageCacheDir(context));
//                Toast.makeText(context,"图片已保存到：" +HeadPresenter.getImageCacheDir(context),Toast.LENGTH_SHORT ).show();
//                super.onPostExecute(o);
            }
        }.execute();
    }
}
